<template>
  <div>
    <el-dialog title="导入客户" :visible.sync="importVisible" width="436px">
      <div v-if="flag == 'import'">
        <el-form
          ref="importForm"
          :model="importForm"
          :rules="rules"
          size="medium"
          :inline="true"
        >
          <div style="margin-top: 20px">
            <div class="textLine">
              1、<a @click="download" class="download">下载模板</a>
              ，按格式准备需要导入的数据
            </div>
            <div style="display: flex" class="textLine">
              2、上传需要导入的文件
              <el-upload
                :action="uploadAction"
                :auto-upload="false"
                ref="upload"
                :data="uploadData"
                :on-success="uploadSuccess"
                :on-error="uploaderror"
                :before-upload="beforeUpload"
                :limit="1"
                :on-exceed="onExceed"
                style="margin-left: 6px"
              >
                <el-button>
                  <svg-icon iconClass="upload-simple"></svg-icon>
                  <span class="ml5"> 选择文件</span>
                </el-button>
              </el-upload>
            </div>
            <div class="textLine customerTag">
              <!-- <el-form-item label="获客平台" prop="platformId"> -->
                3、<span>获客平台</span>
                <el-select v-model="importForm.platformId" placeholder="请选择获客平台" class="textLine"  clearable>
                  <el-option :label="item.scrmGetGuestPlatName" :value="item.scrmGetGuestPlatId"
                            v-for="item in platformList" :key="item.scrmGetGuestPlatId"
                  >
                  </el-option>
                </el-select>
              <!-- </el-form-item> -->
            </div>
<!--            <div class="textLine tagInput">-->
<!--              3、-->
<!--              <span>打标签</span>-->
<!--              <el-input-->
<!--                v-model="importForm.customerTag"-->
<!--                placeholder="请输入"-->
<!--                style="width: 236px; margin-left: 6px"-->
<!--              ></el-input>-->
<!--              <div class="inputInfo">输入多个标签以英文;分隔</div>-->
<!--            </div>-->
            <div class="textLine customerTag" style=" display: flex;">
              <span>4、标签</span>

              <tag-group v-model="importForm.customerTag" style="flex: 1;margin-left: 10px;" />
                            <!-- 3、
                            <span>打标签</span>
                            <tag-group v-model="importForm.customerTag" /> -->
                <!-- <el-button class="button-new-tag" size="small" @click="handleClickLabel" style="margin-left: 10px">
                  <svg-icon icon-class="add"/>
                  添加标签
                </el-button> -->
              <!--          <div class="inputInfo">输入多个标签以英文;分隔</div>-->
            </div>
            <!-- <div class="textLine">
              <div v-if="makeLabelList.length > 0" style="margin-left: 80px">
                <el-tag v-for="item in makeLabelList" :key="item" closable style="margin-bottom: 8px"
                        @close="handleCloseLabel(item)"
                >
                  {{ item }}
                </el-tag>
              </div>
            </div> -->
          </div>
        </el-form>
      </div>
      <div v-if="flag == 'fail'" class="failArea">
        <div class="failTitle">
          <svg-icon iconClass="info"></svg-icon>
          <span> 有{{ failList.length }}条错误信息未成功导入！</span>
        </div>
        <div class="failInfoArea">
          <div v-for="(item, index) in failList" :key="index">
            <p>{{ item }}</p>
          </div>
        </div>
      </div>
      <div v-if="flag == 'success'" class="successArea">
        <div class="successTitle">
          <svg-icon iconClass="success"></svg-icon>
          <span>成功</span>
        </div>
        <div class="successInfo">{{ successMag }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importVisible = false" v-if="flag == 'import'"
          >取消</el-button
        >
        <el-button type="primary" @click="handelConfirm" v-preventReClick="1000"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <!--  添加标签弹窗  -->
    <!-- <MakeLabel :visible.sync="makeLabelVisible" :label.sync="importForm.customerTag" @confirm="makeLabelConfirm"></MakeLabel> -->
  </div>
</template>
<script>
import MakeLabel from "@/components/MakeLabel/index.vue";
import {getPlat, getSource} from "@/api/sourceManage/sourceManage";
import {downLoadLinkFile} from "@/utils/common";
import {getInsuranceType} from "@/utils/auth";
export default {
  name: "ImportCustomer",
  components: {
    MakeLabel,
  },
  props: {
    // 添加标签显隐
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      importForm: {
        // customerTag: undefined,
        customerTag: [],
        platformId: '',
      },
      rules: {},
      options: [],
      platformList: [],
      flag: "import",
      failList: [],
      uploadData: {},
      oldCustomerTag: "",
      successMag: "",
      // 本地调试走代理
      // uploadAction:"/api"+
      //   window.CONFIG.services.admin +
      //   "/admin/adding/batchImport",

      // 线上不走代理
      uploadAction:
        window.globalConfig.BASE_API +
        window.CONFIG.services.admin +
        "/admin/adding/batchImport",


      makeLabelList:[],

      makeLabelVisible:false,
    };
  },
  computed: {
    importVisible: {
      get() {
        if (this.visible) {
          this.importForm.platformId = undefined
          this.changeLine(localStorage.getItem("InsuranceType"))
          this.$nextTick(() => {
            // this.$refs["importForm"].clearValidate();
          });
          this.flag = "import";
        }
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    changeLine(data) {
      this.platformList=[]
        getPlat({ scrmBussLineId: data }).then((res) => {
          this.platformList = res.rows || []
        })
    },
    onOpen() {},
    onClose() {
      this.$refs["importForm"].resetFields();
    },
    close() {
      this.$emit("update:visible", false);
    },
    handelConfirm() {
      if (this.flag == "import") {
        if(!this.importForm.platformId) return this.$message.error('请选择获客平台')
        let flag = true;
        if (this.$refs.upload.$data.uploadFiles.length == 0) {
          this.$message.error("未选择要上传的文件");
          flag = false;
        }
        // this.close();
        //成功 flag ==> success
        //失败 flag ==> fail
        if (flag) {
          // if (this.importForm.customerTag) {
            // this.oldCustomerTag = this.importForm.customerTag;
            // this.importForm.customerTag = this.importForm.customerTag.replace(
            //   /^\s*|\s*$/g,
            //   ""
            // );
            // if (
            //   this.importForm.customerTag.indexOf(";") != -1 ||
            //   this.importForm.customerTag.indexOf("；") != -1
            // ) {
            //   let tagList = [];
            //   let arr = this.importForm.customerTag.split(/[；;]/g);
            //   arr.forEach((item) => {
            //     item = String(item).replace(/^\s*|\s*$/g, "");
            //     if (tagList.indexOf(item) == -1 && item != "") {
            //       tagList.push(item);
            //     }
            //   });
            //   this.importForm.customerTag = tagList;
            // } else {
            //   let tagList = [];
            //   tagList.push(this.importForm.customerTag);
            //   this.importForm.customerTag = tagList;
            // }
          // }
          // this.uploadData["customerTag"] = this.importForm.customerTag || "";
          // this.uploadData["customerTag"] = this.importForm.customerTag || [];
          this.uploadData["platformId"] = this.importForm.platformId || ''
          this.uploadData["InsuranceType"] = getInsuranceType()
          this.uploadData["weGroupTagVOS"] = JSON.stringify(this.importForm.customerTag  || []);
          this.$refs.upload.submit();
        }
      } else {
        this.$parent.getListFn();
        this.close();
      }
    },
    //下载模板
    download() {
      if(window.globalConfig.NODE_ENV === 'production'){
        window.open('https://ark-1308072185.cos.ap-shanghai-fsi.myqcloud.com/scrm/templates/%E5%AF%BC%E5%85%A5%E5%A5%BD%E5%8F%8B%E6%A8%A1%E6%9D%BF.xlsx')
      }else{
        window.open('https://test-ztdata-1308072185.cos.ap-shanghai-fsi.myqcloud.com/scrmtest/scrm-upload/%E5%AF%BC%E5%85%A5%E5%A5%BD%E5%8F%8B%E6%A8%A1%E6%9D%BF.xlsx')
      }
    },
    //文件上传成功
    uploadSuccess(res) {
      this.failList = [];
      if (res.code == 200) {
        this.flag = "success";
        this.successMag = res.msg;
      } else if (res.code == 400) {
        this.failList = res.data;
        this.flag = "fail";
      }
    },
    //文件上传失败
    uploaderror(res) {
      console.log(res);
      // this.close();
      this.importForm.customerTag = this.oldCustomerTag || "";
    },

    beforeUpload(file) {
      console.log(file.name);
      let X = file.name.split(".")[1];
      if (X != "xls" && X != "xlsx") {
        this.$message.error("文件格式不正确");
        this.importForm.customerTag = this.oldCustomerTag || "";
        return false;
      }
    },
    onExceed(file, fileList) {
      this.$message.error("最多只能上传一个文件");
    },

    //打开标签弹窗
    handleClickLabel(){
      this.makeLabelVisible = true
    },

    // 标签弹窗点击确定按钮
    makeLabelConfirm(value){
      this.importForm.customerTag = value
      if (this.importForm.customerTag) {
        this.importForm.customerTag = this.importForm.customerTag.replace(
          /^\s*|\s*$/g,
          ''
        )
        if (
          this.importForm.customerTag.indexOf(';') != -1 ||
          this.importForm.customerTag.indexOf('；') != -1
        ) {
          let tagList = []
          let arr = this.importForm.customerTag.split(/[；;]/g)
          arr.forEach((item) => {
            item = String(item).replace(/^\s*|\s*$/g, '')
            if (tagList.indexOf(item) == -1 && item != '') {
              tagList.push(item)
            }
          })
          this.makeLabelList = tagList
        } else {
          let tagList = []
          tagList.push(this.importForm.customerTag)
          this.makeLabelList = tagList
        }
      }
    },

    // 关闭已经添加的标签
    handleCloseLabel(item){
      this.makeLabelList = this.makeLabelList.filter((x) => {
        return x != item
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.textLine {
  margin: 12px;
  line-height: 34px;
}

.download {
  text-decoration: underline;
  color: #0f40f5;
}

.tagInput {
  position: relative;
}

.inputInfo {
  position: absolute;
  color: #082aff;
  font-size: 12px;
  left: 74px;
  top: 28px;
}

.failArea {
  .failTitle {
    margin: 16px 22px;
    line-height: 40px;
    .svg-icon {
      font-size: 24px;
    }
    span {
      margin-left: 8px;
    }
  }
  .failInfoArea {
    max-height: 204px;
    overflow: hidden;
    p {
      line-height: 26px;
      text-align: left;
      width: 196px;
      margin: 0 auto;
    }
  }
}

.successArea {
  padding: 40px 30px 30px;
  .successTitle {
    margin: 16px 22px;
    line-height: 40px;
    .svg-icon {
      font-size: 24px;
    }
    span {
      margin-left: 8px;
      font-size: 16px;
      font-weight: 800;
    }
  }
  .successInfo {
    text-align: center;
  }
}
</style>
